package cn.com.bocloud.servlet;

import cn.com.bocloud.dao.UserDao;
import cn.com.bocloud.dao.daoimpl.UserDaoImpl;
import cn.com.bocloud.domain.User;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        //response.setContentType("text/json; charset=utf-8");

        System.out.println("doPost");
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");//
        String pwd = request.getParameter("password");//
        System.out.println(name+"=="+pwd);
        //JSONObject jsonData = JSONObject.fromObject(date);
        //System.out.println("jsonData=="+jsonData.toString());
        //String name = jsonData.getString("name");
        //String pwd = jsonData.getString("pwd");
        UserDao userdao = new UserDaoImpl();
        //System.out.println(userdao.toString());
        try {
            User user = userdao.login(name, pwd);
            request.getSession().setAttribute("user",user);
            //返回json数据到前端
            String info = JSONObject.fromObject(user).toString();
            //System.out.println(info);
            response.setContentType("text/html;charset=utf-8");
            System.out.println(info);
            response.getWriter().write(info);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
        doPost(request,response);
    }
}
